<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Target extends Model
{
    protected $table = "c_targets";

    /****
     * @param $data
     * @return bool
     * 添加备忘录
     */
    public function doSetting($data)
    {
        if (isset($data['id']) && !empty($data['id'])) {
            $redata = $this->getInfo($data['id']);
            $redata->case_id = isset($data['case_id'])? $redata->case_id:"";
            $redata->name = $data['name'];
            $redata->values = $data['values'];
            $redata->user_id = $data['user_id'];
            $redata->unit = $data['unit'];
            $redata->remark = isset($data['remark'])?$data['remark']:"";
            $res = $redata->save();
        } else {
            //添加
            $this->case_id = isset($data['case_id'])?$data['case_id']:"";
            $this->name = $data['name'];
            $this->values = isset($data['values'])?$data['values']:"";
            $this->user_id = $data['user_id'];
            $this->unit = $data['unit'];
            $this->remark = isset($data['remark'])?$data['remark']:"";
            $res = $this->save();
            //添加指标值
//            $logs = new TargetLog();
//            $logs->case_id =  isset($data['case_id'])?$data['case_id']:"";
//            $logs->user_id =  $data['user_id'];
//            $logs->target_id =  $this->id;
//            $logs->high =  $data['values'];
//            $logs->remark =  $data['remark'];
//            $logs->ins_times =  date("Y-m-d",time());
//            $logs->save();
        }
        return $res;
    }

    /****
     * @param $data
     * 获取指标列表
     */
    public function getTargetsList($param)
    {
        if(isset($param['user_id'])){
            $list = $this->where([['user_id', '=', $param['user_id']],['case_id', '=', $param['case_id']]])->orderByDesc("id")->get();
        }else{
            $list = $this->where([['case_id', '=', $param['case_id']]])->orderByDesc("id")->get();
        }
        $def  = $this->where([['is_default','=',1]])->orderBy("id")->get()->toArray();
        if (!empty($list)) {
            $list = $list->toArray();
            $list = array_merge($def,$list);
//            foreach($list as $k=>&$v){
//                $tm = strtotime($v['created_at']);
//                $v['tims'] = date("Y",$tm).'年'.date("m",$tm).'月'.date("d",$tm).'日';
//            }
            return $list;
        }
        return $def;
    }

    /***
     * @param $data
     * @return mixed
     * 获取病历夹信息
     */
    public function getInfo($id)
    {
        return $this->where([['id', '=', $id]])->first();
    }

    /***
     * @param $data
     * @return int
     * 删除
     */
    public function delTargets($data)
    {
        (new TargetLog())->where([['target_id', '=', $data['id']]])->delete();
        return $this::destroy($data['id']);
    }

}
